<?php

namespace app\merchants\controller;

use app\common\libs\Excel;
use app\common\libs\ExcelLead;
use app\common\validate\merchant\OrderValid;
use app\merchants\loader\Services;
use think\Exception;

/**
 * 订单管理
 */
class Order extends ApiBase
{

    /**
     * 订单分页列表
     * @return  void
     */
    public function order_page(): void
    {
        try {
            $data = input('get.');

            //需要获取商户id
            $where[] = ['mer_id', '=', $this->adminUser['mer_id']];

            //订单全部匹配
            if (!empty($data['order_no'])) {
                $where[] = ['order_no', '=', $data['order_no']];
            }

            //操作人
            if (!empty($this->adminUser['sub_admin_ids'])) {
                $where[] = ['op_user', 'in', $this->adminUser['sub_admin_ids']];
            }
            if (!empty($data['op_user'])) {
                $where[] = ['op_user', '=', $data['op_user']];
            }

            //门店
            if (!empty($data['shop_id'])) {
                $where[] = ['shop_id', '=', $data['shop_id']];
            }
            //订单全部匹配
            if (isset($data['status'])) {
                if (!empty($data['status']) || $data['status'] == 0) {
                    $where[] = ['status', '=', $data['status']];
                }
            }
            //根据时间搜索
            if (!empty($data['stime']) && empty($data['etime'])) {
                $where[] = ['create_at', '>=', $data['stime']];
            }
            if (empty($data['stime']) && !empty($data['etime'])) {
                $where[] = ['create_at', '<=', $data['etime']];
            }
            if (!empty($data['stime']) && !empty($data['etime'])) {
                $where[] = ['create_at', 'between time', [$data['stime'], $data['etime']]];
            }

            $data = Services::Order()->orderPage($where, $data['page'] ?? 1, $data['page_size'] ?? 30);
            api_result($data);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 订单详情
     * @return  void
     */
    public function order_info(): void
    {
        try {
            $data = input('get.');
            validate(OrderValid::class)->scene('order_info')->check($data);
            $datas = Services::Order()->orderInfo($data['order_no']);
            api_result(API_SUCCESS, '请求成功', $datas);
        } catch (Exception $e) {
            api_result($e);
        }
    }


    /**
     * 验证提交订单名称中的商品数量
     * @param array $detailData
     * @return array
     * @throws Exception
     */
    private function verityOrderDetail(array $detailData): array
    {
        if (empty($detailData)) {
            throw new Exception('商品列表不能为空', API_ERROR);
        }
        $product_list = array_column($detailData, 'num', 'product_code');
        if (count($product_list) !== count($detailData)) {
            throw  new Exception('禁止商品重复添加', API_ERROR);
        }
        foreach ($detailData as $row) {
            $num = (int)$row['num'];
            $verify_num = (int)$row['verify_num'];
            if ($num < 1 || $verify_num < 1) {
                throw  new Exception('商品数量不能小于1', API_ERROR);
            }
            if ((int)$row['num'] !== (int)$row['verify_num']) {
                throw  new Exception('商品数据与验证数量不符', API_ERROR);
            }
        }
        return $detailData;

    }

    /**
     * 订单添加
     */
    public function order_add(): void
    {
        try {
            $data = input('post.');
            validate(OrderValid::class)->scene('order_add')->check($data);
            $data['data'] = $this->verityOrderDetail($data['data']);
            $sum_num = array_sum(array_column($data['data'], 'num'));
            $result = Services::Order()->orderAdd($data, $sum_num, $this->adminUser['admin_id'], $this->adminUser['mer_id']);
            api_result(API_SUCCESS, '请求成功', ['order' => $result]);
        } catch (Exception $e) {
            api_result($e);
        }
    }


    /**
     * 订单导入
     */
    public function order_excel_lead()
    {
        header("Content-type:text/html;charset=utf-8");
        $file = $_FILES['file'];
        try {
            if (!$file) {
                throw new Exception('文件不能为空');
            }
            $data = ExcelLead::getInstance($file['name'] ?? '', $file['tmp_name'] ?? '')
                ->excel_import();
            $objModel = Services::Order();
            [$orderData,$mergeData] = $objModel->mergeArray($this->adminUser['mer_id'], $data);
            $objModel->orderExcelAdd($mergeData, $this->adminUser['mer_id'], $this->adminUser['admin_id'],$orderData);
            api_result(API_SUCCESS, '导入成功');
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 订单确认提交
     */
    public function order_submit()
    {
        $param = input('post.');
        try {
            $order_nos = !is_array($param['order_nos']) ? explode(',', $param['order_nos']) : $param['order_nos'];
            Services::Order()->orderSubmit($order_nos, $this->adminUser['mer_id'], $this->adminUser['admin_id'], $param['memo'] ?: '');
            api_result(API_SUCCESS, '请求成功');
        } catch (Exception $e) {
            api_result($e);
        }
    }


    /**
     * 订单导出模板
     */
    public function order_excel_send()
    {
        try {
            //导出所有商品
            $res = Excel::getInstance()
                ->sendType('excel')
                ->excelTitles(['shop_code' => '门店编码', 'code' => '商品编码', 'warn_num' => '数量'])
                ->filename('订单模板' . date('Y-m-d H:i:s'))
                ->excelData([])
                ->send();
            if (!$res) {
                throw  new Exception('导出失败', API_ERROR);
            }
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 订单删除
     */
    public function order_del()
    {
        $param = input('post.');
        try {
            $order_nos = !is_array($param['order_nos']) ? explode(',', $param['order_nos']) : $param['order_nos'];
            Services::Order()->orderDel($order_nos, $this->adminUser['mer_id']);
            api_result(API_SUCCESS, '请求成功');
        } catch (Exception $e) {
            api_result($e);
        }
    }
}
